package com.likou;

import java.util.*;

/**
 * https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长子串 的长度。
 */
public class 无重复字符的最长子串 {
    public static void main(String[] args) {
        String s = "googlescholar";
        int i = lengthOfLongestSubstring1(s);
        System.out.println(i);
    }

    /**
     * 双循环暴力求解发
     */
    public static int lengthOfLongestSubstring(String s) {
        if(s.length()==0 || s == null){
            return 0;
        }
        int max = 1;
        ArrayList<Character> str = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            for (int j = i+2; j <= s.length(); j++) {
                String sub = s.substring(i,j);
                char[] chars = sub.toCharArray();
                for (int i1 = 0; i1 < chars.length; i1++) {
                    if (!str.contains(chars[i1])) {
                        str.add(chars[i1]);
                        max = Math.max(max, str.size());
                       if(i1 ==  chars.length-1) {
                           str.clear();
                       }
                    }else {
                        str.clear();
                        break;
                    }
                }
            }
        }
        return max;
    }

    /**
     * 滑动窗口
     */
    public static int lengthOfLongestSubstring1(String s) {
        int max = 0;
        Map<Character,Integer> map = new HashMap<>();
        for(int end = 0,start = 0;end < s.length(); end++){
            char c = s.charAt(end);
            if(map.containsKey(c)){
                start = Math.max(start,map.get(c));
            }
            max = Math.max(max,end - start + 1);
            map.put(c,end+1);
        }
        return max;
    }

}
